package com.neusoft.interceptor;


import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class SupervisorInterceptor implements HandlerInterceptor {

    private RedisTemplate<String, Object> redisTemplate;

    public SupervisorInterceptor(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        log.info(request.getMethod());
        if(request.getMethod().equalsIgnoreCase("OPTIONS")){
            return true;
        }
        if ("false".equals(request.getHeader("direct-call"))) {
            return true; // 如果匹配，放行请求
        }
        //获取请求头中的令牌
        String token = request.getHeader("token");
        log.info("当前token为：{}", token);

        Map<String, Object> map = new HashMap<>();
        try {
            if(token!=null) {
                JWTUtil.verify(token);
                DecodedJWT verify = JWTUtil.verify(token);
                String account = verify.getClaim("phoneNumber").asString(); // 前面存的时候转字符串了
                String password = verify.getClaim("password").asString();
                log.info("解析token");
                log.info("用户phoneNumber：{}", account);
                log.info("用户password: {}", password);
                log.info("去验证todo...");
                String redistoken = (String) redisTemplate.opsForValue().get(account);
                if (redistoken!=null&&redistoken.equals(token)) {
                    log.info("验证成功");
                    return true;
                } else {
                    log.info("token已过期验证成功");
                    throw new Exception();
                }
            }
            else{
                map.put("code", 401);
                map.put("msg", "未携带签名");
            }
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "签名不一致");
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "令牌过期");
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            map.put("code",401);
            map.put("msg", "算法不匹配");
        } catch (InvalidClaimException e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "失效的payload");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 401);
            map.put("msg", "token无效");
        }

        map.put("sstatus", false);

        //响应到前台: 将map转为json
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
        return false;
    }
}

